﻿@inherits BasePropertyEditor

@using RapidCMS.UI.Components.Editors
@using RapidCMS.UI.Helpers

<div class="input-group">
    <div class="input-group-prepend">
        <button type="button" class="btn btn-outline-primary" @onclick="@Generate">
            <i class="icon ion-md-key"></i> Generate new password
        </button>
    </div>
    <input value=@GetValueAsString()
           @onchange=OnChange
           class="form-control @(CssHelper.GetValidationClass(State))" />

    @foreach (var message in GetValidationMessages())
    {
        <div class="invalid-feedback">
            @message
        </div>
    }
</div>

@code {
    private void Generate()
    {
        SetValueFromString(string.Join("-", Guid.NewGuid()
            .ToString()
            .Split('-')
            .Select((x, i) => (i % 2 == 0) ? x : x.ToUpper())));
    }

    private void OnChange(ChangeEventArgs args)
    {
        var value = (string)args.Value;

        SetValueFromString(value);

        if (value == "123456")
        {
            // adding custom validation messages is easy using the EditContext
            // these messages are added next to messages from ValidationAttributes
            EditContext.AddValidationMessage(Property, "Easy passwords are not allowed");
        }
    }

    protected override Task OnParametersSetAsync()
    {
        return base.OnParametersSetAsync();
    }
}
